package com.pianke.yc.test.Classess;

import android.content.Context;
import android.util.Log;

import com.pianke.yc.test.Data.JobJson;

import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by YC on 2016/4/3.
 */
public class JobLab {

    private static final String Tag = "JobLab";
    private static final String FILENAME = "job.json";

    private static JobLab mJobLab;
    private Context mContext;
    private JobJson mJobJson;

    public ArrayList<Job> mJobs;

    public JobLab(Context context) {
        mContext = context;
        mJobJson = new JobJson(mContext, FILENAME);
        try {
            mJobs = mJobJson.loadJobs();
        } catch (IOException e) {
            mJobs = new ArrayList<>();
            Log.d(Tag, "File open fail");
        }
    }

    public static JobLab get(Context c) {
        if (mJobLab == null)
            mJobLab = new JobLab(c);
        return mJobLab;
    }

    public ArrayList<Job> getJobs(int id, int limit) {
        ArrayList<Job> list = new ArrayList<>();
        id--;
        for (Job j : mJobs) {
            if (limit < 0) break;
            if (id == j.id) {
                list.add(j);
                id--;
                limit--;
            }
        }
        return list;
    }


    public Job getJob(int id) {
        for (Job job : mJobs) {
            if (job.id == id) {
                return job;
            }
        }
        return null;
    }

    public void addJob(Job j) {
        mJobs.add(j);
    }

    public boolean savaJobs() {
        try {
            mJobJson.saveJob(mJobs);
            Log.i(Tag, "Job save to file");
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public void deleteJob(Job j) {
        mJobs.remove(j);
    }

    public int getId() {
        if (mJobs != null && mJobs.size() > 0)
            return mJobs.get(0).id;
        return -1;
    }

}
